import { computed } from 'vue';

export default (props: any) => {
    const { $fn, $db, $global, $model } = props.ujt;

    function getApiUrl() {
        if ($db[props.opt.channel].dbtype == 'file') {
            return '/api/asaichannel/file';
        } else {
            return '/api/asaichannel/sqlite';
        }
    }
    function getFieldArr() {
        return Object.keys($db[props.opt.channel].rfdata.lang);
    }
    function getFieldData() {
        return getFieldArr().join('-');
    }
    function getQueryData(fty: number = 0) {
        const queryData: any = {
            model: props.opt.model,
            channel: props.opt.channel,
        };
        fty && (queryData.field = getFieldData());
        return queryData;
    }
    function getQueryString(fty: number = 0) {
        return '?' + new URLSearchParams(getQueryData(fty)).toString();
    }
    function initChannel() {
        $db[props.opt.channel] = {
            stat: 0,
            fetch: fetchContent,
            setpage: setPage,
            cmPageList: [],
        };
        $fn.initmodel(
            props.opt.model + '/channel/' + props.opt.channel + '.json'
        ).then((res: any) => {
            Object.assign($db[props.opt.channel], res);
            $db[props.opt.channel].rfdata = {
                rule: {
                    ...($model.data.asai.asaichannel?.rule || {}),
                    ...($db[props.opt.channel]?.rule || {}),
                },
                lang: computed(() => {
                    return {
                        ...$global.lang[props.opt.channel].data,
                        ...$global.lang.asaichannel.data,
                    };
                }),
            };
            $db[props.opt.channel].stat = 1;
        });
    }
    function initAddChannel() {
        const tmpFn: any = getDefaultValue();
        $db[props.opt.channel].rfdata.data = {};
        Object.keys($db[props.opt.channel].rfdata.lang).forEach(
            (key: string) => {
                $db[props.opt.channel].rfdata.data[key] = tmpFn[key]
                    ? tmpFn[key]()
                    : '';
            }
        );
    }
    function readItem(sn: any) {
        if (sn) {
            try {
                $fn.api['webserver']
                    .apiGet(
                        getApiUrl() + '/select/' + sn + '/',
                        getQueryData(1)
                    )
                    .then((res: any) => {
                        // if ($db[props.opt.channel].dbtype == 'file') {
                        //     $db[props.opt.channel].rfdata.data = JSON.parse(
                        //         res.data[0][getFieldArr()?.[1]]
                        //     );
                        // } else {
                        $db[props.opt.channel].rfdata.data = res.data[0];
                        // }
                    });
            } catch (e) {}
        }
    }
    function setChannelClass(value: any, tty: number = 0) {
        $fn.setquery({ fl: value });
        $db[props.opt.channel].fetch(0);
        if (props.opt.one) {
            setChannelHash('list', tty);
        } else {
            initAddChannel();
        }
    }
    function fetchContent(pctype: number = 1, svty: number = 0) {
        const fTit: string = getFieldArr()?.[1] || 'tit';
        $fn.api['webserver']
            .apiGet(getApiUrl() + '/select/', {
                ...getQueryData(),
                svty,
                fd: 'sn-' + fTit,
                ps: $db[props.opt.channel].cmPageSize,
                ...$global.location?.query,
            })
            .then((res: any) => {
                // if ($db[props.opt.channel].dbtype == 'file') {
                //     $db[props.opt.channel].list = res.data.map((el: any) => {
                //         return JSON.parse(el?.[fTit] || '{}');
                //     });
                // } else {
                $db[props.opt.channel].list = res.data;
                // }
                fetchContentCount(pctype);
            });
    }
    function fetchContentCount(pctype: number = 1) {
        if (!pctype) {
            $fn.api['webserver']
                .apiGet(getApiUrl() + '/select/', {
                    ...getQueryData(),
                    fd: 'sn',
                    ...$global.location?.query,
                    sx: '',
                    sxty: '',
                    pc: 0,
                    pg: 0,
                    ps: Number($db[props.opt.channel].config?.pmax) || 10000,
                })
                .then((res: any) => {
                    $fn.setquery({ pc: res.data?.length }, 1);
                    // setPage($global.location.query?.pg || 1);
                });
        }
    }

    function setPage(page: number) {
        $fn.setquery({ pg: page || 1 }, 1);
        fetchContent($global.location.query?.pc || 0);
    }

    function delItem(sn: any) {
        $fn.api['webserver']
            // .apiPost(getApiUrl() + '/delete/' + sn)
            .apiPost(getApiUrl() + '/delete/' + sn + getQueryString(1))
            .then((res: any) => {
                fetchContent(0, 1);
            });
    }
    function editItem(sn: any, tty: number = 0) {
        if (props.opt.one) {
            setChannelHash('edit', tty);
        }
        $fn.setquery({ show: sn, showty: '1' }, 1);
        readItem(sn);
    }

    function optConfirm(item: any) {
        $global.pop['popconfirm' + props.opt.channel].stat = 1;
        $global.pop['popconfirm' + props.opt.channel].full = 2;
        $global.pop['popconfirm' + props.opt.channel].con = item.con;
        $global.pop['popconfirm' + props.opt.channel].fn = item.fn;
    }
    // tty=-1强制不跳转路由
    function setChannelHash(type: string, tty: number = 0) {
        if (tty > -1) {
            $fn.sethash(
                $global.location.hash.replace(
                    '/' + $global.location.hasharr[tty || props.opt.ty || 1],
                    '/' + type
                )
            );
        }
    }
    function setShow(sn: any, tty: number = 0) {
        if (props.opt.one) {
            setChannelHash('show', tty);
        }
        $fn.setquery({ show: sn, showty: '' }, 1);
        readItem(sn);
    }
    function searchSubmit() {
        if (!$global.location.query.ssty && $global.location.query.ss) {
            $global.location.query.ssty = $db[props.opt.channel]?.sss?.[1];
        }
        $fn.setquery({ pg: 1 }, 1);
        $db[props.opt.channel].fetch(0);
    }
    function addContent(tty: number = 0) {
        if (checkContent()) {
            $fn.api['webserver']
                .apiPost(
                    getApiUrl() +
                        '/insert/' +
                        $db[props.opt.channel].rfdata.data.sn +
                        getQueryString(1),
                    $db[props.opt.channel].rfdata.data
                )
                .then((res: any) => {
                    $global.msg.fn({
                        type: 'ok',
                        con: $global.lang.asai.successadd,
                    });
                    $db[props.opt.channel].fetch(0, 1);
                    if (props.opt.one) {
                        setChannelHash('list', tty);
                    } else {
                        initAddChannel();
                    }
                });
        }
    }
    function getRequire() {
        return Object.entries($db[props.opt.channel].rfdata.rule)
            .filter((el: any) => el[1]?.require)
            .map((elm: any) => elm[0]);
    }
    function checkContent() {
        const requires = getRequire();
        if (requires.length) {
            for (let i = 0; i < requires.length; i++) {
                if (!$db[props.opt.channel].rfdata.data[requires[i]]) {
                    $global.msg.fn({
                        type: 'err',
                        con: $fn.lg(
                            'asai.checkrequire',
                            $db[props.opt.channel].rfdata.lang?.[requires[i]] ||
                                requires[i]
                        ),
                    });
                    return false;
                }
            }
        }
        return true;
    }
    function editContent(tty: number = 0) {
        if (checkContent()) {
            $fn.api['webserver']
                .apiPost(
                    getApiUrl() +
                        '/update/' +
                        $db[props.opt.channel].rfdata.data.sn +
                        '/' +
                        getQueryString(1),
                    $db[props.opt.channel].rfdata.data
                )
                .then((res: any) => {
                    $global.msg.fn({
                        type: 'ok',
                        con: $global.lang.asai.successedit,
                    });
                    $db[props.opt.channel].fetch(1, 1);
                    if (props.opt.one) {
                        setChannelHash('list', tty);
                    }
                });
        }
    }
    function getDefaultValue() {
        const tmpVal: any = {
            sn: () => {
                return $fn.As.Uuid(props.opt.channel.substring(0, 2));
            },
            hi: () => 1,
            xi: () => 1,
            yi: () => 0,
            tm: () => Date.now(),
            tx: () => Date.now(),
            us: () => $global.user.info.us,
        };
        if ($global.location.query.fl) {
            tmpVal.class = () => $global.location.query.fl;
        }
        return tmpVal;
    }
    return {
        initChannel,
        initAddChannel,
        setChannelClass,
        delItem,
        editItem,
        readItem,
        optConfirm,
        setPage,
        setShow,
        fetchContent,
        searchSubmit,
        addContent,
        editContent,
        getDefaultValue,
        setChannelHash,
    };
};
